package com.xyht.medicine_management_system.modules.user.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@Log4j2
public class SMSUtil {
    @Value("${aliyun.appKey}")
    private String appKey;
    @Value("${aliyun.appSecret}")
    private String appSecret;
    static com.aliyun.dysmsapi20170525.Client client = null;

    @Bean
    public void createClient() throws Exception {
        Config config = new Config()
                // 您的 AccessKey ID
                .setAccessKeyId(appKey)
                // 您的 AccessKey Secret
                .setAccessKeySecret(appSecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        client =  new com.aliyun.dysmsapi20170525.Client(config);
    }

    public Boolean sendSMSCode(String tel,String code) throws Exception {
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName("星源慧通")
                .setTemplateCode("SMS_464106207")
                .setPhoneNumbers(tel)
                .setTemplateParam("{code:"+code+"}");
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse response = client.sendSmsWithOptions(sendSmsRequest, runtime);
            JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(response));
            Map<String,Object> body = JSONObject.parseObject(jsonObject.getString("body"),Map.class);
            log.debug("body:"+JSON.toJSONString(body));
            if (!body.get("code").equals("OK")){
                return false;
            }
        } catch (TeaException error) {
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return true;
    }
}
